In this notebook, you will compile the visualizations from the previous analysis into functions to create a Panel dashboard.
# imports
import panel as pn
pn.extension('plotly')
import plotly.express as px
import pandas as pd
import hvplot.pandas
import matplotlib.pyplot as plt
import os
from pathlib import Path
from dotenv import load_dotenv
from matplotlib.figure import Figure
# Initialize the Panel Extensions (for Plotly)
import panel as pn
pn.extension("plotly")
# Read the Mapbox API key
load_dotenv()
map_box_api = os.getenv("MAPBOX_API_KEY")
px.set_mapbox_access_token(map_box_api)
# Import the CSVs to Pandas DataFrames
file_path = Path("Data/toronto_neighbourhoods_census_data.csv")
to_data = pd.read_csv(file_path, index_col="year")
file_path = Path("Data/toronto_neighbourhoods_coordinates.csv")
df_neighbourhood_locations = pd.read_csv(file_path)
In this section, you will copy the code for each plot type from your analysis notebook and place it into separate functions that Panel can use to create panes for the dashboard.
These functions will convert the plot object to a Panel pane.
Be sure to include any DataFrame transformation/manipulation code required along with the plotting code.
Return a Panel pane object from each function that can be used to build the dashboard.
Note: Remove any .show() lines from the code. We want to return the plots instead of showing them. The Panel dashboard will then display the plots.
# Getting the data from the top 10 expensive neighbourhoods
ten_expensive_neighbourhoods = to_data.groupby("neighbourhood").mean().sort_values(by="average_house_value", ascending=False).reset_index().head(10)
# Calculate the number of dwelling types units per year
dwellings_per_year = to_data.groupby("year").sum().drop(columns=["average_house_value", "shelter_costs_owned", "shelter_costs_rented" ])
# Calculate the average monthly shelter costs for owned and rented dwellings
monthly_shelter_cost_per_year = to_data[["shelter_costs_owned","shelter_costs_rented"]].groupby("year").mean()
# Define Panel visualization functions
def neighbourhood_map():
"""Neighbourhood Map"""
# Calculate the mean values for each neighborhood
mean_data_neighbourhoods = to_data.groupby("neighbourhood").mean().reset_index()
neighbourhood_with_location = pd.concat([mean_data_neighbourhoods, df_neighbourhood_locations ], join="inner", axis="columns")
return px.scatter_mapbox(
neighbourhood_with_location,
lat="lat",
lon="lon",
color="average_house_value", title="Average House Value in Toronto"
)
def create_bar_chart(data, title, xlabel, ylabel, color):
"""
Create a barplot based in the data argument.
Input:
data = DataFrame to use for plotting the data
title = Chart Title
xlabel = Label for X Axis
ylabel = Label for Y Axis
color = Colour of the bar chart
"""
return data.hvplot.bar( xlabel=xlabel, ylabel=ylabel, color=color, title=title, rot=90)
def create_line_chart(data, title, xlabel, ylabel, color):
"""
Create a line chart based in the data argument.
Input:
data = DataFrame to use for plotting the data
title = Chart Title
xlabel = Label for X Axis
ylabel = Label for Y Axis
color = Colour of the bar chart
"""
return data.hvplot.line( xlabel=xlabel, ylabel=ylabel, color=color, title=title, rot=90)
def average_house_value():
"""Average house values per year."""
average_house_value = to_data["average_house_value"].groupby("year").mean()
return create_line_chart(data=average_house_value, title="Average House Value in Toronto ",
xlabel="Year", ylabel="Average House Value", color="blue")
def average_value_by_neighbourhood():
"""Average house values by neighbourhood."""
avg_house_value_by_neighbourhood = to_data[["neighbourhood","average_house_value"]].reset_index()
return avg_house_value_by_neighbourhood.hvplot.line(x="year", y="average_house_value", xlabel="Year", ylabel="Average House Value", groupby="neighbourhood")
def number_dwelling_types():
"""Number of dwelling types per year"""
dwelling_types_per_year = to_data.drop(columns=["average_house_value", "shelter_costs_owned", "shelter_costs_rented" ])
return dwelling_types_per_year.hvplot.bar(groupby="neighbourhood",rot=90, ylabel="Dwelling Type Units", xlabel="Year", height=500)
def average_house_value_snapshot():
"""Average house value for all Toronto's neighbourhoods per year."""
return px.bar(to_data, x="neighbourhood", y="average_house_value",color="average_house_value", facet_row=to_data.index,height=1000, title="Average House Values in Toronto Per Neighbourhood" )
def top_most_expensive_neighbourhoods():
"""Top 10 most expensive neighbourhoods."""
ten_expensive_neighbourhoods = to_data.groupby("neighbourhood").mean().sort_values(by="average_house_value", ascending=False).reset_index().head(10)
return ten_expensive_neighbourhoods.hvplot.bar(rot=90, ylabel="Average House Value", xlabel="Neighbourhood", y="average_house_value", x="neighbourhood",height=500)
def sunburts_cost_analysis():
"""Sunburst chart to conduct a costs analysis of most expensive neighbourhoods in Toronto per year."""
ten_most_expensive_neighbourhoods_per_year = to_data.sort_values(by="average_house_value", ascending=False).groupby('year').head(10)
return px.sunburst(
ten_most_expensive_neighbourhoods_per_year,
path=[ten_most_expensive_neighbourhoods_per_year.index, 'neighbourhood'], values='average_house_value', color='average_house_value', color_continuous_scale='blues',
height=500
)
# YOUR CODE HERE!
In this section, you will combine all of the plots into a single dashboard view using Panel. Be creative with your dashboard design!
# Create a Title for the Dashboard
title = "## Real Estate Analysis of Toronto from 2001 to 2016"
# Define a welcome text
welcome_text = "*This dashboard presents the visual analysis of the historical house values, dwelling types per neighbourhood and dwelling costs in Toranto according to census data from 2001 to 2016. You can navigate through tabs to explore more details around real estate market in these 6 years.*"
#Create a welcome tab
welcome_tab = pn.Column(welcome_text, neighbourhood_map())
#Yearly Market Analysis Tab
yearly_market_analysis_tab = pn.Column(
pn.Row(
create_bar_chart(dwellings_per_year.loc[2001], title="Dwelling Types in Toranto in 2001", xlabel="2001", ylabel="Dwelling Type Units", color="red"),
create_bar_chart(dwellings_per_year.loc[2006], title="Dwelling Types in Toranto in 2006", xlabel="2006", ylabel="Dwelling Type Units", color="blue")
),
pn.Row(
create_bar_chart(dwellings_per_year.loc[2011], title="Dwelling Types in Toranto in 2011", xlabel="2011", ylabel="Dwelling Type Units", color="yellow"),
create_bar_chart(dwellings_per_year.loc[2016], title="Dwelling Types in Toranto in 2016", xlabel="2016", ylabel="Dwelling Type Units", color="pink")
)
)
#Yearly Market Analysis Tab
shelter_vs_house_analysis_tab = pn.Column(
create_line_chart(data=monthly_shelter_cost_per_year["shelter_costs_owned"], title="Average Monthly Shelter Cost for Owned Dwellings in Toronto ",
xlabel="Year", ylabel="Average Monthly Shelter Costs", color="red"),
create_line_chart(data=monthly_shelter_cost_per_year["shelter_costs_rented"], title="Average Monthly Shelter Cost for Rented Dwellings in Toronto ",
xlabel="Year", ylabel="Average Monthly Shelter Costs", color="yellow"),
average_house_value()
)
#Neigbourhood Analysis
neighbourhood_analysis_tab = pn.Row(pn.Column(average_value_by_neighbourhood(),number_dwelling_types()), average_house_value_snapshot())
#Top Expensive Neighbourhoods
expensive_neighbourhood_tab = pn.Row(top_most_expensive_neighbourhoods(), sunburts_cost_analysis())
dashboard_tabs = pn.Tabs(
(
"Welcome",
welcome_tab
),
(
"Yearly Market Analysis",
yearly_market_analysis_tab
),
(
"Shelter Costs vs House Value",
shelter_vs_house_analysis_tab
),
(
"Neighbourhood Analysis",
neighbourhood_analysis_tab
),
(
"Top Expensive Neighbourhood",
expensive_neighbourhood_tab
),
)
dashboard = pn.Column(title, dashboard_tabs)
# Create the main dashboard
dashboard
dashboard.servable()
Note: Some of the Plotly express plots may not render in the notebook through the panel functions.
However, you can test each plot by uncommenting the following code
# create_bar_chart(data, title, xlabel, ylabel, color)
#create_bar_chart(dwellings_per_year.loc[2001], title="Dwelling Types in Toranto in 2001", xlabel="2001", ylabel="Dwelling Type Units", color="red")
# # Bar chart for 2001
# create_bar_chart(df_dwelling_units.loc[2001], "Dwelling Types in Toronto in 2001", "2001", "Dwelling Type Units", "red")
# # Bar chart for 2006
# create_bar_chart(df_dwelling_units.loc[2006], "Dwelling Types in Toronto in 2006", "2006", "Dwelling Type Units", "blue")
# # Bar chart for 2011
# create_bar_chart(df_dwelling_units.loc[2011], "Dwelling Types in Toronto in 2011", "2011", "Dwelling Type Units", "orange")
# # Bar chart for 2016
# create_bar_chart(df_dwelling_units.loc[2016], "Dwelling Types in Toronto in 2016", "2016", "Dwelling Type Units", "magenta")
# create_line_chart(data, title, xlabel, ylabel, color)
# # Line chart for owned dwellings
# create_line_chart(df_avg_costs["shelter_costs_owned"], "Average Monthly Shelter Cost for Owned Dwellings in Toronto", "Year", "Avg Monthly Shelter Costs", "blue")
# # Line chart for rented dwellings
# create_line_chart(df_avg_costs["shelter_costs_rented"], "Average Monthly Shelter Cost for Rented Dwellings in Toronto", "Year", "Avg Monthly Shelter Costs", "orange")
# average_house_value()
# average_value_by_neighbourhood()
# number_dwelling_types()
# average_house_value_snapshot()
# top_most_expensive_neighbourhoods()
# sunburts_cost_analysis()